//
//  RouFIle.swift
//  ONESwift
//
//  Created by wangkun on 2017/7/20.
//  Copyright © 2017年 wangkun. All rights reserved.
//

import UIKit

public enum DirectoryTo {
    case document
    case cache
    case temp
}

public let fileManage = FileManager.default

/// document路径，最后带/
public let DocumentPath = NSHomeDirectory() + "/Documents/"
/// bundle路径，最后带/
public let BundlePath = (Bundle.main.resourcePath ?? "") + "/"
/// 缓存路径，最后带/
public let CachePath = (NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first ?? "") + "/"
/// 临时路径，最后带/
public let TempPath = NSTemporaryDirectory()

extension FileManager {
    
    public typealias SaveFileBlock = (_ path: String, _ finished: Bool) -> Void
    
    /// 保存文件到内存
    ///
    /// - Parameters:
    ///   - data:   文件data
    ///   - to:     保存的主路径
    ///   - folder: 文件保存得地址
    public func saveFile(_ data: Data?, _ to: DirectoryTo, _ folder: String, block: SaveFileBlock) {
        if data == nil {
            return
        }
        var path = folder
        if path.first() == "/" {
            path.removeFirst()
        }
        
        switch to {
        case .document:
            path = "\(DocumentPath)\(path)"
        case .cache:
            path = "\(CachePath)\(path)"
        case .temp:
            path = "\(TempPath)\(path)"
        }
        
        let filePath = URL(fileURLWithPath: path).deletingLastPathComponent().path
        
        ///创建文件夹
        try! fileManage.createDirectory(atPath: filePath, withIntermediateDirectories: true, attributes: nil)

        try? data?.write(to: URL(fileURLWithPath: path))
        
        block(path, fileManage.fileExists(atPath: path))
    }
}
